import { contextBridge, ipcRenderer } from 'electron'
// import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api: WindowApi = {
  axiosRequest: async (config) => {
    const { data, headers } = await ipcRenderer.invoke('axios', config)
    if (Array.isArray(headers['set-cookie'])) {
      for (const cookieStr of headers['set-cookie']) {
        const arr = cookieStr.split(';')[0].split('=')
        localStorage.setItem(arr[0], arr[1])
      }
    }
    return data
  },
  getUrlFileBuffer: (config) => ipcRenderer.invoke('getUrlFileBuffer', config),
  getCacheFileBuffer: (config) => ipcRenderer.invoke('getCacheFileBuffer', config),
  cookies: (url: string) => ({
    getValue: async (name: string) => {
      const cookies = await (ipcRenderer.invoke as InvokeGetCookies)('getCookies', { url, name })
      if (cookies.length) {
        return cookies[0].value
      }
      return ''
    }
  }),
  apptitlebar: () => ({
    minimize: () => ipcRenderer.send('minimize'),
    maximizeOrUnmaximize: () => ipcRenderer.send('maximizeOrUnmaximize'),
    close: () => ipcRenderer.send('close'),
    isMaximized: (callback) =>
      ipcRenderer.on('maximized', (_, isMaximized) => callback(isMaximized))
  })
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    // contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  // window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
